import { Component, OnInit, ViewEncapsulation, ChangeDetectorRef, ViewChild } from '@angular/core';
import { HttpService } from '../../service/http.service';
import { Router } from '@angular/router';
import { parse } from 'url';
import { ToastComponent, ToastService } from 'ngx-weui';
import { MaskComponent } from 'ngx-weui'
declare const wx: any;

@Component({
  selector: 'app-scanoutpatientpay',
  templateUrl: './scanoutpatientpay.component.html',
  styleUrls: ['./scanoutpatientpay.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class ScanoutpatientpayComponent implements OnInit {
  @ViewChild('lll') loadingToast: ToastComponent;
  @ViewChild('jiaoflonding') jiaofloading: ToastComponent;


  @ViewChild('mask') mask: MaskComponent;

  scanoutpatientpayurl = 'hisinfo!getPayReceiptInfo';
  payurl = 'weixin!pays';
  backpayurl = 'hisinfo!getPaymentPayModify';
  type1: number = 3;
  paystate: number;
  djh: string;
  je: string;
  no: string;
  type: number;
  zfzt: boolean;
  total = 0;
  djlist: any[] = [];
  //已缴费医嘱list
  yjflist: any[] = [];
  //未缴费医嘱list
  wjflist: any[] = [];
  wjtotal:any;
  wj:any=0;
  state: boolean = false;
  outpatientlistinfo: {
    YZID: string,
    YZLX: string,
    YZMC: string
    ZJ: string
  }
  outpatientlist: any;//[]=[this.outpatientlistinfo];

  doctorname: string;
  outpatienttime: string;
  scanname: string;

  res: any = {
    cho2: true,
    worldpost: '1',
    contact: '1',
    country: '1',
    agree: true
  };

  info: any[] = [
    { 'name': '检查费', 'price': '500' },
    { 'name': '西药费', 'price': '300' },
    { 'name': '挂号费', 'price': '200' }
  ];

  cheinfo: any[] = [];

  constructor(private httpservice: HttpService, private router: Router, private srv: ToastService, private cdr: ChangeDetectorRef) { }

  ngOnInit() {

    this.type = 0;
    this.getoutpatientpay();
    // this.scanname = sessionStorage.getItem('scanname');
    this.scanname = '徐特';
    
  }

  getoutpatientpay() {
    (<ToastComponent>this['loadingToast']).onShow();
    let data = "{BRID:'" + sessionStorage.getItem('brid') + "',DAYS:'30',JSKLB:'重庆市医保'}";
    this.httpservice.httpPost(this.scanoutpatientpayurl, data).subscribe(res => {
      console.log(res)
      if (this.httpservice.dataFilter(res)) {
        sessionStorage.setItem('scanoutpatientpay', JSON.stringify(res.data));
        this.outpatientlist = res.data.YZLIST;
        if(this.outpatientlist.length==0){
          this.zfzt = false;
        }
        for (var i = 0; i < res.data.YZLIST.length; i++) {
          var total = 0;
          this.wjtotal = 0;
          this.zfzt = true;
          for (var j = 0; j < res.data.YZLIST[i].FMLIST.length; j++) {
            if (res.data.YZLIST[i].FMLIST[j].ZFZT == "0") {
              var price = parseFloat(res.data.YZLIST[i].FMLIST[j].JE);
              this.wjtotal  += price;
              console.log("yj",this.wjflist);
            } else {
              console.log("yj",this.yjflist);
              //this.zfzt = false;
              
            }
            var price = parseFloat(res.data.YZLIST[i].FMLIST[j].JE);
            total += price;
          
          }
          if( this.wjtotal!=0){
            res.data.YZLIST[i].WJF = 0;
            this.state = false;
            this.type = 0;
            this.wjflist.push(res.data.YZLIST[i]);
          }else{
            this.yjflist.push(res.data.YZLIST[i]);
            res.data.YZLIST[i].WJF = 1;
            this.type = 2;
            this.state = true;
          }
          this.wj +=this.wjtotal;
          res.data.YZLIST[i].TOTAL = total.toFixed(2);
        }
        if (this.zfzt) {
          this.outpatientlist = res.data.YZLIST;

        } else {
          this.type = 2;
        }
        (<ToastComponent>this['loadingToast']).onHide();
        this.doctorname = res.data.YSXM;
        this.outpatienttime = res.data.YYSJ;
        for (var i = 0; i < this.wjflist.length; i++) {
          for (var j = 0; j < this.wjflist[i].DJLIST.length; j++) {
            if (this.wjflist[i].DJLIST) { }
            this.djlist.push({ djh: this.wjflist[i].DJLIST[j].DJH, je: this.wjflist[i].DJLIST[j].JE });

          }
        }

        console.log("djlist",this.djlist);
        //单据号去重
        var hash = {};
        this.djlist = this.djlist.reduce(function (item, next) {
          hash[next.djh] ? '' : hash[next.djh] = true && item.push(next);
          return item
        }, []);

        for (var j = 0; j < this.djlist.length; j++) {
          var price = parseFloat(this.djlist[j].je);
          this.total += price;
        }
      }
    });
    sessionStorage.setItem('totals', this.total.toString());
  }

  pay() {
    this.type = 1;
    let data = "{body:'诊间支付',brid:'" + sessionStorage.getItem('brid') + "',total_fee:'" + this.wj.toFixed(2) + "',openid:'" + sessionStorage.getItem('openid') + "'}";
    let fatherthis = this;

    setTimeout(() => {
      this.type = 0;
    }, 5000);
    this.httpservice.httpPost(this.payurl, data).subscribe(res => {
      console.log('res', res);
      if (this.httpservice.dataFilter(res)) {
        wx.config({
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: res.data.appId, // 必填，公众号的唯一标识
          timestamp: res.data.timeStamp, // 必填，生成签名的时间戳
          nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
          signature: res.data.signature,// 必填，签名，见附录1
          jsApiList: ['chooseWXPay'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
        });
        wx.chooseWXPay({
          appId: res.data.appId,
          timestamp: res.data.timeStamp,
          nonceStr: res.data.nonceStr,
          package: res.data.package,
          signType: res.data.signType,
          paySign: res.data.paySign,
          success: function (r) {
            if (r.errMsg == "chooseWXPay:ok") {
              // (<ToastComponent>fatherthis['loadingToast']).onShow();
              fatherthis.backpay(res.data.out_trade_no, fatherthis);
            } else {
              alert(r.errMsg);
            }

          },
          cancel: function (r) {
            fatherthis.cancel(r);
          },
          fail: function (r) {

            fatherthis.cancel(r)
          }
        });
      }
    });
  }
  cancel(reson) {
    this.type = 0;

  }
  unique5(arr1) {

  }
  backpay(no, llo) {
    this.type = 3;
    (<ToastComponent>this['jiaofloading']).onShow();
    this.cdr.markForCheck();
    this.cdr.detectChanges();

    //
    console.log(this.djlist.sort());
    let data2 = "{NO:" + JSON.stringify(this.djlist.sort()) + ",BRID:'" + sessionStorage.getItem('brid') + "',SFGH:'0',JSKH:'',JSFS:'1',JYLSH:'" + no + "'}";
    this.httpservice.httpPost(this.backpayurl, data2).subscribe(res => {
      if (res.state == "F") {
        this.type = 0;
        this.cdr.markForCheck();
        this.cdr.detectChanges();
        alert("缴费失败" + JSON.stringify(res.error));
      } else if (res.state == "T") {
        //   wx.closeWindow();
        //  this.router.navigate(["/payrsult"]);
        for(var i = 0; i < this.wjflist.length; i++){
          this.yjflist.push(this.wjflist[i]);
        }
        this.wjflist=null;
        (<ToastComponent>this['jiaofloading']).onHide();
       // this.getoutpatientpay();
        this.cdr.markForCheck();
        this.cdr.detectChanges();
        

        // window.location.href = "http://yuyue.cqjydata.com/#/payrsult"

      }

    });
  }
  close() {
    wx.closeWindow();
  }
  yjfscanoutpatientpayinfo(i){
    sessionStorage.setItem('scanoutpatientpayinfo', JSON.stringify(this.yjflist[i].FMLIST));
    sessionStorage.setItem('mzh', JSON.stringify(this.yjflist[i].MZH));
    this.router.navigate(['outpatientpay/scanoutpatientpayinfo']);
  }
  wjfscanoutpatientpayinfo(i) {
    sessionStorage.setItem('scanoutpatientpayinfo', JSON.stringify(this.wjflist[i].FMLIST));
    sessionStorage.setItem('mzh', JSON.stringify(this.wjflist[i].MZH));
    this.router.navigate(['outpatientpay/scanoutpatientpayinfo']);
  }

  checkall(ev) {
    this.cheinfo.push(this.info)
    this.info.forEach(x => x.state = ev.target.checked);
  }

  checkedall() {
    return this.info.every(_ => _.state);
  }
}
